package cn.zn.framework.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.zn.base.common.constant.Constants;
import cn.zn.base.common.utils.ResultUtil;
import cn.zn.base.factory.AsyncManager;
import cn.zn.framework.bean.LoginUser;
import cn.zn.framework.factory.OperateLogFactory;
import cn.zn.framework.service.JwtTokenService;
import cn.zn.user.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author zn-admin
 */
@Component
public class CustomLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private JwtTokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (ObjectUtil.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            SysUser sysUser = loginUser.getTheUser();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.instance().execute(OperateLogFactory.recordLogin(userName, sysUser.getUserName(), Constants.LOGOUT, "退出成功"));
        }
        ResultUtil.renderString(response, JSONUtil.toJsonStr(ResultUtil.success("退出成功")));
    }

}
